2020-02-15-AFNetworking添加SecurityPolicy解决上传文件时https请求Status Code 200(正常)Request failed unacceptable content-type问题

使用 https://github.com/AFNetworking/AFNetworking 上传文件时https请求Status Code 200(正常)Request failed unacceptable content-type问题
需要在原代码中加入以下codeblock来解决
最终代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer= [AFHTTPRequestSerializer serializer];
//往下 2020.1.14更新此codeblock
//添加securityPolicy
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
securityPolicy.validatesDomainName = NO;
securityPolicy.allowInvalidCertificates = YES;
manager.securityPolicy = securityPolicy;
//需要请求前面加上定制化的配置
manager.responseSerializer.acceptableContentTypes= [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
//往上 2020.1.14更新此codeblock
NSDictionary *dict = @{@"key":@"id111111",@"type":@"file4what"};
NSMutableData *data = [NSMutableData data];
NSMutableData *fileData = [NSMutableData dataWithContentsOfFile:@"filePath"];
NSString *spaceString1 = @"\n\n---------------------------------------------------------1---------------------------------------------------------\n\n";
[data appendData:[spaceString1 dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:fileData];
NSString *spaceString2 = @"\n\n---------------------------------------------------------split line---------------------------------------------------------\n\n";
[data appendData:[spaceString2 dataUsingEncoding:NSUTF8StringEncoding]];
// 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
// 要解决此问题,
// 可以在上传时使用当前的系统事件作为文件名
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置时间格式
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"abc%@.log", str];
[manager POST:@"https://www.xxx.com/app/upload.php" parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//上传
/*
此方法参数
1. 要上传的[二进制数据]
2. 对应网站上[upload.php中]处理文件的[字段"Filedata"]
3. 要保存在服务器上的[文件名]
4. 上传文件的[mimeType]
*/
[formData appendPartWithFileData:data name:@"Filedata" fileName:fileName mimeType:@"text/html"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"上传日志成功 %@", responseObject);
//返回json
NSDictionary *jsonDic = responseObject;
//OK了开始处理
int ret = [jsonDic[@"code"] intValue];
if (ret == 0) {
NSString *xxx = jsonDic[@"xxx"];
//......
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"上传日志失败 %@", error);
}];

参考链接
https://www.jianshu.com/p/3bc4243e4c05
https://github.com/AFNetworking/AFNetworking